#include "StdAfx.h"
#include "ScriptModule.h"
#include "Console.h"
#include "Clipboard.h"
#include "../ScriptBackend_BasicTypes/ScriptBackend.h"
#include "../ScriptBackend_CEGUI/ScriptBackend.h"

PTR pLS = 0;
boost::signal<void(const std::string& msg)> CA::ScriptModule::OnScriptError;
boost::signal<void(const std::string& msg)> CA::ScriptModule::OnStdException;

PTR CA::ScriptModule::GetLuaState()
{
	return pLS;
}

void Console_OnRequestEval(const std::string& cmd)
{
		
	try
	{
		lua_State *l = (lua_State*)pLS;
		if(luaL_dostring(l,cmd.c_str())!=0)
		{	
			lua_pop(l,1);
			std::string errormsg = lua_tostring(l, 0);
			
			static std::string header = "[script error] ";		
			CA::Console::Print(header+errormsg);
			CA::ScriptModule::OnScriptError(errormsg);
		}
	}
	catch(std::exception* ex)
	{
		static std::string header = "[std::exception] ";
		std::string msg = ex->what();
		CA::Console::Print(header+msg);
		CA::ScriptModule::OnStdException(msg);
	}
}

class Test
{
private:
	int value;
public:
	int GetValue()const{return value;}
	void SetValue(int va){value=va;}
};

bool CA::ScriptModule::Load( PTR lua_state )
{
	if(pLS!=0)
		return false;

	lua_State* pL = 0;
	if(lua_state==0)
		pL=luaL_newstate();
	else
		pL=(lua_State*)lua_state;

	//////////////////////////////////////////////////////////////////////////
	//begin registration	

	{
		using namespace luabind;
		open(pL);

		module(pL)
			[
				namespace_("Console")
				[					
					def("Eval",&Console::Eval),
					def("Print",&Console::Print),
					def("Hide",&Console::Hide),
					def("Show",&Console::Show),
					def("Shutdown",&Console::Shutdown),
					def("Cls",&Console::Cls)
				]
				,				
				namespace_("Clipboard")
				[
					def("SetData",&Clipboard::SetData),
					def("GetData",&Clipboard::GetData)
				]				
			];		

		//ScriptBackend::BasicType_Module::Load(pL);
		ScriptBackend::CEGUI_Module::Load(pL);		
	}
	
	
	//finish registration
	//////////////////////////////////////////////////////////////////////////

	pLS = pL;

	Console::OnRequestEval.connect(&Console_OnRequestEval);
	return true;
}